package com.example.androidgeneric;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;

public class VolleyPostJsonResult<T extends Serializable> extends StringRequest {

	private static final int SOCKET_TIMEOUT_MS = 5000;
	
	private HashMap<String, String> input;
	private onResultValue<T> onResult;
	
	private Gson gson = new Gson();
	private Type dataType;
	private ArrayList<T> getList;
	
	public interface onResultValue<T> {
		public void onJsonResult(ArrayList<T> result);
	}
	
	public VolleyPostJsonResult(Type DataType, String url, Listener<String> listener,
			ErrorListener errorListener) {
		super(Method.POST, url, listener, errorListener);
		this.dataType = DataType;
		RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
		setRetryPolicy(policy);
	}
	
	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		
		try {
			String resultString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
			Log.e("GetData", resultString);
			
			getList = gson.fromJson(resultString, dataType);
			Log.e("ListSize", String.valueOf(getList.size()));
			onResult.onJsonResult(getList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return super.parseNetworkResponse(response);
	}
	
	public void setOnResult(onResultValue<T> onResult) {
		this.onResult = onResult;
	}
	
	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		return getInput();
	}

	public HashMap<String, String> getInput() {
		return input;
	}

	public void setInput(HashMap<String, String> input) {
		this.input = input;
	}

}
